from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, SelectField
from wtforms.validators import DataRequired, Length, ValidationError
from application.users.models import Users, Class

# 注册表单
class RegisterForm(FlaskForm):
	username = StringField('username', validators=[DataRequired(message='Username required'), Length(max=128, message='fullname can not more than 128 digits')])
	password = PasswordField('password', validators=[DataRequired(message='Password required'), Length(min=6, message='password can not less than 6 digits')])
	fullname = StringField('fullname', validators=[DataRequired(message='Fullname required'), Length(max=128, message='fullname can not more than 128 digits')])
	submit = SubmitField('Register')

	# 验证用户名是否存在
	def validate_username(self, field):
		username = field.data
		user = Users.query.filter_by(username=username).first()
		if user:
			raise ValidationError('This user is already exist!')


class LoginForm(FlaskForm):
	username = StringField('username', validators=[DataRequired(message='Username required')])
	password = PasswordField('password', validators=[DataRequired(message='Password required')])
	remember_me = BooleanField('remember_me')
	submit = SubmitField('Login')


class SelectClassForm(FlaskForm):
	select_class = SelectField('please select your class', coerce=int)
	submit = SubmitField('Select')

	def __init__(self, *args, **kwargs):
		super(SelectClassForm, self).__init__(*args, **kwargs)
		result_list = [(item.id, item.name) for item in Class.query.order_by(Class.name).all()]
		self.select_class.choices = result_list
